package org.demo.rc.client;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JLabel;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

/**
 * 图像标签
 * @author  
 * @date    2010-10-23
 * @file    org.demo.rc.ImageLabel.java
 */
public class JImagePanel extends JLabel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private BufferedImage image;
	private BufferedImage defaultImage;
	int left = 0, top = 0;
	/**
	 * 构造函数
	 */
	public JImagePanel(){
		InputStream in = this.getClass().getResourceAsStream("blank.jpg");
		try {
			JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
			defaultImage = decoder.decodeAsBufferedImage();
			int width = defaultImage.getWidth();
			int height = defaultImage.getHeight();
			Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
			left = (int)(screen.getWidth()-width)/2;
			top = (int)(screen.getHeight()-height)/2 - 40;
		} catch (ImageFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try { if (in != null)in.close(); } catch( Exception e){}
		}
	}
	/**
	 * 绘制组件
	 */
	@Override
	public void paint(Graphics g) {
		if (image != null){
			g.drawImage(image, 0, 0, this);
		} else if (defaultImage != null ){
			g.drawImage(defaultImage, left, top, this);
		} else {
			super.paint(g);
		}
	}
	/**
	 * 设置图像
	 * @param image
	 */
	public void setImage(BufferedImage image){
		this.image = image;
		if (image == null){
			return;
		}
		this.setPreferredSize(new Dimension(image.getWidth(),
				                            image.getHeight()));
	}
}
